import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import BiMap from 'bidirectional-map'
import _ from 'lodash'

export const usePriceSummaryStore = defineStore('priceSummary', () => {
  const priceSummaryData = ref([])
  const fields = ref({})
  const setPriceSummaryData = (newData) => priceSummaryData.value = newData
  const contracts = computed(() => {
    return Array.from(new Set(priceSummaryData.value.map(item => item['合同号'])))
  })

  const resetFields = () => fields.value = new BiMap({
    contract: '合同号',
    factory: '加工厂',
    weft: '纱支',
    weftFactory: '纱厂',
    ingredient: '成份',
    quantity: '實際数量',
    weftCost: '纱款金额',
    deliveryCost: '运费金额',
    model: '款号',
    client: '客戶',
    deliveryDay: 'OK办寄出日期',
  })
  const setFields = (newFields) => fields.value = new BiMap(newFields)
  const fieldsObject = ref({})
  watch(() => fields.value, (newVal, prevVal) => {
    // console.log('storePrevValW1', prevVal)
    // console.log('storeNewValW1', newVal)
    if (!_.isEmpty(newVal)) {
      fieldsObject.value = newVal.getObject()
      // console.log('fieldsObject.value', fieldsObject.value)
    }
  }, { immediate: true, deep: true, flush: 'pre' })
  const getFieldValue = (key) => fields.value.get(key)
  const getVal = (obj, key) => _.get(obj, getFieldValue(key))

  return {
    priceSummaryData,
    setPriceSummaryData,
    contracts,
    fields,
    resetFields,
    setFields,
    fieldsObject,
    getFieldValue,
    getVal
  }
})
